<?php

namespace app\common\model;

use think\Model;

/**
 * user_id:用户标识符
 * rec_user_id:推荐人的用户标识符
 * user_name:昵称
 * user_uniid:用户编号
 * password:密码
 * password2:二级密码
 * id_number:身份证号
 * phone:联系电话
 * mail_address:电邮地址
 * qq：QQ号
 * weixin:微信号
 * user_type:用户种类，user(用户),agent(代理),admin(管理员),superuser(超级管理员)
 * account_type:账号类型，普通会员，理财会员
 * user_status:账号状态，未认证，已认证，被冻结
 * salt:密码盐值
 * 外部关系：
 * sent_mails:发送的邮件
 * mails：收到的邮件
 * articles：发布的公告
 * cards：拥有的银行卡
 * vaild_card:当前有效银行卡
 * son_users:发展的用户
 * parent_user：自己的推荐人
 * command_users:作为代理，旗下的用户
 * agent：自己的代理上级
 * cash_flows:自己的资金变动情况
 * confirmed_cash_flows:管理员确认的资金变动情况.
 * awards：自己的所有奖金
 * charges：自己的所有充值记录
 * confirmed_charges：自己发起的所有充值记录
 * consumes：自己的所有消费记录
 * encashments：自己的所有提现记录
 * confirmed_encashments:自己确认的所有提现
 * owned_line:自己下属的队列
 * tickets:自己的所有排队票
 * agent_applications:自己的所有代理申请
 * confirmed_applications:自己批准的所有代理申请.
 */
class User extends Model
{
    protected $insert = ['user_type' => 'user'];
    //密码加密部分
    private function password_hash($password, $salt)
    {
        return hash('sha256', $password.$salt);
    }
    public function setPasswordAttr($value, $data)
    {
        if (empty($this->salt)) {
            $this->salt = $this->getSalt();
        }

        return $this->password_hash($value, $this->data['salt']);
    }
    public function setPassword2Attr($value, $data)
    {
        if (empty($this->salt)) {
            $this->salt = $this->getSalt();
        }

        return $this->password_hash($value, $this->data['salt']);
    }
    /**
     * 自动获得对应上级代理.
     */
    public function setRecUserIdAttr($value, $data)
    {
        $usr = self::get($value);
        if (empty($usr)) {
            $this->data['agent_id'] = 0;
            $this->path = '0,';

            return 0;
        }
        if ($usr->user_type == 'user') {
            $this->data['agent_id'] = $usr->agent_id;
        } else {
            $this->data['agent_id'] = $value;
        }
        $this->path = $usr->path.$usr->user_id.',';

        return $value;
    }

    /**
     * 检测密码
     *
     * @param string $value 密码
     *
     * @return bool 此密码是否正确
     */
    public function checkPassword($value)
    {
        return $this->password == $this->password_hash($value, $this->salt);
    }
    /**
     * 检测二级密码
     *
     * @param string $value 密码
     *
     * @return bool 此密码是否正确
     */
    public function checkPassword2($value)
    {
        return $this->password2 == $this->password_hash($value, $this->salt);
    }

    //状态封装
    public static $user_type_category = [0 => 'user', 1 => 'agent', 2 => 'admin', 3 => 'superuser'];
    public function getUserTypeAttr($value)
    {
        $data = self::$user_type_category;

        return $data[$value];
    }
    public function setUserTypeAttr($value, $data)
    {
        $catedata = self::$user_type_category;
        $catedata = array_flip($catedata);
        if ($value != 'user') {
            $this->owned_line()->save();
        }

        return $catedata[$value];
    }
    //状态封装
    public static $user_type_cn_category = [0 => '普通用户', 1 => '代理商家', 2 => '管理员', 3 => '超级管理员'];
    public function getUserTypeCnAttr($value,$data)
    {
        $catedata = self::$user_type_cn_category;

        return $catedata[$data['user_type']];
    }
    public static $user_status_category = array(0 => '未认证', 1 => '已认证', 2 => '被冻结');
    public function getUserStatusAttr($value)
    {
        $data = self::$user_status_category;

        return $data[$value];
    }
    public function setUserStatusAttr($value)
    {
        $data = self::$user_status_category;
        $data = array_flip($data);
        if ($value == '被冻结') {
            $tickets = $this->tickets()->where('ticket_status', 0)->order('rank','DESC')->select();
            foreach ($tickets as $ticket) {
                $ticket->ticket_status = '被删除';
                $ticket->save();
            }
        }
        if($value == '已认证')
        {
            if($this->user_status=='未认证')
            {
              $this->confirm_time=date('Y-m-d H:i:s');
            }
        }

        return $data[$value];
    }
    public static $account_type_category = [0 => '普通会员', 1 => '理财会员'];
    public function getAccountTypeAttr($value)
    {
        $data = self::$account_type_category;

        return $data[$value];
    }
    public function setAccountTypeAttr($value)
    {
        $data = self::$account_type_category;
        $data = array_flip($data);

        return $data[$value];
    }
    /**
     * [examine_cash 从流水验证一个人的余额].
     *
     * @return array 此人的余额
     */
    public function examine_cash()
    {
        $cash_flows = $this->cash_flows;
        $sum_money_cash = 0;
        $sum_line_cash = 0;
        foreach ($cash_flows as $cash_flow) {
            if ($cash_flow->cash_flow_status == '已完成' or $cash_flow->cash_flow_status == '正在进行') {
                if ($cash_flow->cash_type == '财富币') {
                    $sum_money_cash += $cash_flow->cash_value;
                } else {
                    $sum_line_cash += $cash_flow->cash_value;
                }
            }
        }

        return ['money_cash' => $sum_money_cash, 'line_cash' => $sum_line_cash];
    }
    /**
     * 生成盐（随机字符串）.
     *
     * @return string 盐值
     */
    protected static function getSalt()
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $noncestr = '';
        for ($i = 0; $i < 16; ++$i) {
            $noncestr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $noncestr;
    }
    //所有的外部关系
    public function son_users()
    {
        return $this->hasMany('User', 'rec_user_id', 'user_id');
    }
    public function getAllSonUsersAttr($value)
    {
        if (empty($value)) {
            $son = $this->all_son_users()->select();
            $this->all_son_users = $son;

            return $son;
        }

        return $value;
    }
    public function getSonUserCountAttr($value)
    {
        if (empty($value)) {
            $son = $this->son_users()->count();
            $this->son_user_count = $son;

            return $son;
        }

        return $value;
    }
    public function getDepthAttr($value)
    {
        if (empty($value)) {
            $depth = substr_count($this->path, ',');
            $this->depth = $depth;

            return $depth;
        }

        return $value;
    }
    public function all_son_users()
    {
        return self::where('path', 'like', $this->path.$this->user_id.',%');
    }
    public function parent_user()
    {
        return $this->belongsTo('User', 'rec_user_id', 'user_id');
    }
    public function command_users()
    {
        return $this->hasMany('User', 'agent_id', 'user_id');
    }
    public function agent()
    {
        return $this->belongsTo('User', 'agent_id', 'user_id');
    }
    public function mails()
    {
        return $this->hasMany('Mail', 'target_user_id', 'user_id');
    }
    public function sent_mails()
    {
        return $this->hasMany('Mail', 'send_user_id', 'user_id');
    }
    public function articles()
    {
        return $this->hasMany('Article', 'user_id');
    }
    public function cards()
    {
        return $this->hasMany('Card', 'user_id');
    }
    public function vaild_card()
    {
        return $this->hasOne('Card', 'user_id')->where('card_status', 1);
    }
    public function cash_flows()
    {
        return $this->hasMany('CashFlow', 'user_id');
    }
    public function confirmed_cash_flows()
    {
        return $this->hasMany('CashFlow', 'confirm_user', 'user_id');
    }
    public function owned_line()
    {
        return $this->hasOne('Line', 'user_id');
    }
    public function tickets()
    {
        return $this->hasMany('LineTicket', 'user_id');
    }
    public function agent_applications()
    {
        return $this->hasMany('AgentApplication', 'user_id');
    }
    public function confirmed_applications()
    {
        return $this->hasMany('AgentApplication', 'confirm_user', 'user_id');
    }
    public function awards()
    {
        return $this->hasMany('Award', 'user_id')->where('cash_flow_type', 0);
    }
    public function charges()
    {
        return $this->hasMany('Charge', 'user_id')->where('cash_flow_type', 1);
    }
    public function confirmed_charges()
    {
        return $this->hasMany('Charge', 'confirm_user', 'user_id')->where('cash_flow_type', 1);
    }
    public function consumes()
    {
        return $this->hasMany('Consume', 'user_id')->where('cash_flow_type', 2);
    }
    public function encashments()
    {
        return $this->hasMany('Encashment', 'user_id')->where('cash_flow_type', 3);
    }
    public function confirmed_encashments()
    {
        return $this->hasMany('Encashment', 'confirm_user', 'user_id')->where('cash_flow_type', 3);
    }
}
